package com.szyt.basicframe.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szyt.basicframe.pojo.entity.SysUser;
import com.szyt.basicframe.mapper.SysUserMapper;
import com.szyt.basicframe.pojo.request.usermanagement.CreateUserRequest;
import com.szyt.basicframe.pojo.request.usermanagement.SearchUserRequest;
import com.szyt.basicframe.pojo.request.usermanagement.UpdateUserRequest;
import com.szyt.basicframe.pojo.vo.UserDetailsVO;
import com.szyt.basicframe.pojo.vo.UserListItemVO;
import com.szyt.basicframe.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szyt.basicframe.util.IdUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mx
 * @since 2025-06-29
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    //创建用户
    @Transactional
    @Override
    public boolean createUser(CreateUserRequest request) {
        SysUser user = new SysUser();
        BeanUtil.copyProperties(request, user);
        user.setId(IdUtil.getId());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setLocked(false);
        return save(user);
    }

    //根据id列表查询用户
    @Transactional
    @Override
    public List<SysUser> findUserByIds(List<Long> userIds) {
        if (CollectionUtil.isEmpty(userIds)) return new ArrayList<>();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysUser::getId, userIds);
        return list(queryWrapper);
    }


    //根据id查询用户
    @Transactional
    @Override
    public SysUser findUserById(Long userId) {
        if (userId == null) return null;
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getId, userId);
        return getOne(queryWrapper);
    }

    //根据筛选条件（这里根据userName模糊查询） 检索用户列表
    @Transactional
    @Override
    public IPage<UserListItemVO> searchUsers(SearchUserRequest request) {
        Page<SysUser> page = new Page<>(request.getPageNum(), request.getPageSize());
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(request.getUserName()), SysUser::getUserName, request.getUserName())
                .orderByDesc(SysUser::getCreateTime);
        //原始分页信息
        Page<SysUser> sourcePage = page(page, queryWrapper);
        //转换数据列表
        IPage<UserListItemVO> resultPage = sourcePage.convert(entity -> {
            UserListItemVO item = new UserListItemVO();
            BeanUtil.copyProperties(entity, item);
            return item;
        });
        return resultPage;
    }

    //获取用户详情
    @Transactional
    @Override
    public UserDetailsVO getUserDetails(Long id) {
        SysUser user = findUserById(id);
        UserDetailsVO result = new UserDetailsVO();
        BeanUtil.copyProperties(user, result);
        return result;
    }

    /**
     * 查询用户名已被使用
     * @param userId 新增用户时，参数值为null；编辑用户时，参数为要修改用户的id
     * @param userName 新增或修改后的用户名
     * @return
     */
    @Transactional
    @Override
    public boolean existUserName(Long userId, String userName) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(userId != null, SysUser::getId, userId)
                .eq(SysUser::getUserName, userName);
        return count(queryWrapper) > 0;
    }


    /**
     * 编辑用户的基本信息
     * @param request
     * @return
     */
    @Transactional
    @Override
    public boolean updateUser(UpdateUserRequest request) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getId, request.getId())
                .set(SysUser::getUserName, request.getUserName())
                .set(SysUser::getNickName, request.getNickName())
                .set(SysUser::getSex, request.getSex())
                .set(SysUser::getTel, request.getTel())
                .set(SysUser::getEmail, request.getEmail())
                .set(SysUser::getLocked, request.getLocked());
        return update(updateWrapper);
    }

    @Transactional
    @Override
    public boolean disableUser(Long userId) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getId, userId)
                .set(SysUser::getLocked, true);
        return update(updateWrapper);
    }

    @Transactional
    @Override
    public boolean enableUser(Long userId) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getId, userId)
                .set(SysUser::getLocked, false);
        return update(updateWrapper);
    }


    @Transactional
    @Override
    public boolean delete(Long userId) {
        return removeById(userId);
    }
}
